import os
import platform
import psutil
import socket
from typing import Dict, Any

class SystemInfo:
    """系统信息工具类"""
    
    @staticmethod
    def get_system_info() -> Dict[str, Any]:
        """
        获取系统信息
        
        Returns:
            包含系统信息的字典
        """
        try:
            # 获取系统基本信息
            system_info = {
                "platform": platform.system(),
                "platform_release": platform.release(),
                "platform_version": platform.version(),
                "architecture": platform.architecture()[0],
                "processor": platform.processor(),
                "machine": platform.machine(),
                "node": platform.node(),
            }
            
            # 获取内存信息
            virtual_memory = psutil.virtual_memory()
            system_info["memory"] = {
                "total": virtual_memory.total,
                "available": virtual_memory.available,
                "used": virtual_memory.used,
                "percent": virtual_memory.percent
            }
            
            # 获取磁盘信息（Windows系统使用C:盘）
            try:
                disk_usage = psutil.disk_usage('C:')
                system_info["disk"] = {
                    "total": disk_usage.total,
                    "used": disk_usage.used,
                    "free": disk_usage.free,
                    "percent": disk_usage.percent
                }
            except Exception as e:
                system_info["disk"] = {"error": f"获取磁盘信息失败: {e}"}
            
            # 获取CPU信息
            system_info["cpu"] = {
                "cores": psutil.cpu_count(logical=False),
                "logical_cores": psutil.cpu_count(logical=True),
                "usage": psutil.cpu_percent(interval=1)
            }
            
            # 获取网络信息
            try:
                hostname = socket.gethostname()
                ip_address = socket.gethostbyname(hostname)
                system_info["network"] = {
                    "hostname": hostname,
                    "ip_address": ip_address
                }
            except:
                system_info["network"] = {"error": "无法获取网络信息"}
            
            return system_info
            
        except Exception as e:
            return {"error": f"获取系统信息失败: {e}"}
    
    @staticmethod
    def get_process_info() -> list:
        """
        获取进程信息
        
        Returns:
            进程信息列表
        """
        try:
            processes = []
            for proc in psutil.process_iter(['pid', 'name', 'username', 'cpu_percent', 'memory_percent']):
                try:
                    process_info = proc.info
                    processes.append(process_info)
                except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                    pass
            
            # 按CPU使用率排序
            processes.sort(key=lambda x: x.get('cpu_percent', 0) or 0, reverse=True)
            return processes[:10]  # 返回前10个进程
            
        except Exception as e:
            return [{"error": f"获取进程信息失败: {str(e)}"}]
    
    @staticmethod
    def get_disk_info() -> list:
        """
        获取磁盘分区信息
        
        Returns:
            磁盘分区信息列表
        """
        try:
            partitions = []
            for partition in psutil.disk_partitions():
                try:
                    usage = psutil.disk_usage(partition.mountpoint)
                    partition_info = {
                        "device": partition.device,
                        "mountpoint": partition.mountpoint,
                        "fstype": partition.fstype,
                        "total": usage.total,
                        "used": usage.used,
                        "free": usage.free,
                        "percent": usage.percent
                    }
                    partitions.append(partition_info)
                except PermissionError:
                    continue
            
            return partitions
            
        except Exception as e:
            return [{"error": f"获取磁盘信息失败: {str(e)}"}]
    
    @staticmethod
    def format_bytes(size: int) -> str:
        """
        格式化字节大小为易读格式
        
        Args:
            size: 字节大小
            
        Returns:
            格式化后的字符串
        """
        # 字节单位
        units = ['B', 'KB', 'MB', 'GB', 'TB']
        unit_index = 0
        
        while size >= 1024 and unit_index < len(units) - 1:
            size /= 1024
            unit_index += 1
        
        return f"{size:.2f} {units[unit_index]}"
